package com.fa4j.system.account.controller;

import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.Page;
import com.fa4j.common.web.annotation.ApiMethod;
import com.fa4j.common.web.model.AppType;
import com.fa4j.system.account.model.Account;
import com.fa4j.system.account.model.AccountLog;
import com.fa4j.system.account.model.AccountLogQuery;
import com.fa4j.system.account.repository.AccountLogRepository;
import com.fa4j.system.account.repository.AccountRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("system/account/log")
@RequiredArgsConstructor
public class AccountLogController {

    private final AccountLogRepository accountLogRepository;
    private final AccountRepository accountRepository;

    @GetMapping("page")
    @ApiMethod(name = "系统账户日志-分页查询", type = AppType.MANAGE)
    public Page<AccountLog> page(AccountLogQuery query) {
        Page<AccountLog> result = accountLogRepository.queryPage(query);
        fillName(result.getRecords());
        return result;
    }

    private void fillName(List<AccountLog> list) {
        List<Long> accountIds = list.stream().map(AccountLog::getAccountId).toList();
        List<Account> accountList = accountRepository.queryByIds(accountIds);
        list.forEach(log -> {
            log.setAppName(log.getAppType().getName());
            accountList.stream()
                    .filter(account -> Objects.equals(log.getAccountId(), account.getId()))
                    .findFirst().ifPresent(account -> log.setAccountName(account.getNickname()));
        });
    }

    @ApiMethod(name = "系统账户日志-详情查询", type = AppType.MANAGE)
    @GetMapping("{id}")
    public AccountLog detail(@PathVariable Long id) {
        AccountLog accountLog = accountLogRepository.findById(id)
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("权限日志"));
        fillName(List.of(accountLog));
        return accountLog;
    }

}
